package com.sea.example.service.impl;

import com.alibaba.fastjson2.JSON;
import com.sea.example.bean.MenuApiResponse;
import com.sea.example.service.ReptileService;
import com.sea.example.utils.HttpClientUtil;
import com.sea.example.utils.ThreadPoolExecuteUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: hcxu
 * Time: 2024/9/12 5:12 PM
 */
@Service
@Slf4j
public class reptileServiceImpl implements ReptileService {
    private static final String filePath = "/Users/mac/Desktop/game/";

    @Override
    public void runReptileTask(String url) throws InterruptedException {
        //拿到所有列表信息
        String menuListString = HttpClientUtil.postRequestJson("https://pan.gbtgame.me/api/fs/list", "");
        MenuApiResponse menuApiResponse = JSON.parseObject(menuListString, MenuApiResponse.class);
        //maxSize=11907427
        List<MenuApiResponse.Content> content = menuApiResponse.getData().getContent();
        //需要下载的列表目录信息,todo 先拿一个测试
        //List<MenuApiResponse.Content> downMenuList = content.subList(4,5);
        List<MenuApiResponse.Content> downMenuList = content.stream().filter(e -> e.getSize() <= 11907427L).collect(Collectors.toList());
        //使用线程处理，一个目录一个线程
        syncReptileTask(downMenuList);
    }

    public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException {
        String file = "https://pan.gbtgame.me/d/【2018年3月〜2018年5月】/红色警戒2＋尤里的复仇 ———— 全剧情动画中文完整版(OC制作).torrent?sign=Kdb0c2THEQJnSOOXD2vdCv9nRA1GgFuJ4P6M7wsq2x4=:0";
        String encodedPath  = file.replace(" ", "%20");
        HttpClientUtil.downloadFile(encodedPath, null, "/Users/mac/Desktop/红色警戒2＋尤里的复仇 ———— 全剧情动画中文完整版(OC制作).torrent");
    }
    public static void syncReptileTask(List<MenuApiResponse.Content> list) throws InterruptedException {
        Queue<MenuApiResponse.Content> queue = new ConcurrentLinkedQueue<>(list);
        int size = ThreadPoolExecuteUtils.newExecutorInstance().getCorePoolSize() + 1;
        size = Math.min(size, queue.size());
        CountDownLatch downLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            ThreadPoolExecuteUtils.newExecutorInstance().execute(() -> {
                try {
                    while (!queue.isEmpty()) {
                        MenuApiResponse.Content content = queue.poll();
                        String menuName = content.getName();
                        if(!menuName.contains("PikPak")){
                            log.info("目录名称：{}", menuName);
                            //获取子目录
                            Map<String,Object> map = new HashMap<>();
                            map.put("path",menuName);
                            String jsonParam = JSON.toJSONString(map);
                            String menuListString = HttpClientUtil.postRequestJson("https://pan.gbtgame.me/api/fs/list", jsonParam);
                            MenuApiResponse menuApiResponse = JSON.parseObject(menuListString, MenuApiResponse.class);
                            //获取sign和文件名称
                            List<MenuApiResponse.Content> fileList = menuApiResponse.getData().getContent();
                            for (MenuApiResponse.Content fileData : fileList) {
                                String sign = fileData.getSign();
                                String fileName = fileData.getName();
                                //拼接下载地址
                                StringBuffer stringBuffer = new StringBuffer("https://pan.gbtgame.me/d/");
                                stringBuffer.append(menuName).append("/");
                                stringBuffer.append(fileName).append("?sign=");
                                stringBuffer.append(sign);
                                String menuPath = filePath + "/";
                                createDirectoryIfNotExists(menuPath);
                                //log.info("文件名:{},下载地址:->>>>>>>>>>>{}",fileName,stringBuffer);
                                String filePathName = menuPath + fileName;
                                File directory = new File(filePathName);
                                if (!directory.exists()) {
                                    // 对URL中的特殊字符进行编码
                                    String encodedPath  = stringBuffer.toString().replace(" ", "%20");
                                    HttpClientUtil.downloadFile(encodedPath, null, filePathName);
                                    log.info("目录:{},文件:{},下载完成",menuName,fileName);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                    log.error("报错：{}", e);
                } finally {
                    downLatch.countDown();
                }
            });
        }
        downLatch.await();
    }

    public static void createDirectoryIfNotExists(String directoryPath) {
        // 创建File对象
        File directory = new File(directoryPath);

        // 判断目录是否存在
        if (!directory.exists()) {
            // 如果目录不存在，创建目录
            if (directory.mkdirs()) {
                //System.out.println("目录创建成功: " + directoryPath);
            } else {
                //System.out.println("目录创建失败: " + directoryPath);
            }
        } else {
            //System.out.println("目录已存在: " + directoryPath);
        }
    }
}
